# coding=utf-8
__author__ = 'liubin'

import datetime
from sqlalchemy import Column, BigInteger, ForeignKey, DateTime
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql.expression import text
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.hybrid import hybrid_method
from project.tools import JsonpickleMixin

class BaseModel(JsonpickleMixin):
    id = Column('id', BigInteger, primary_key=True)

    @declared_attr
    def insertUser(cls):
        return Column('insert_user', BigInteger,)
    #insert_user = Column('insert_user', BigInteger, ForeignKey('m_user.id'))

    @declared_attr
    def insertUserObj(cls):
        backref = 'inserted' + cls.__name__ + 's'
        return relationship("User", backref=backref, primaryjoin ="foreign(User.id)==%s.insertUser" % cls.__name__)
    #insert_user_obj = relationship("User", backref="insert_users")
    #insertTime = Column('insert_time', DateTime, default=datetime.datetime.now)

    @declared_attr
    def insertTime(cls):
        return Column('insert_time', DateTime, default=datetime.datetime.now, server_default=text('NOW()'))

    @declared_attr
    def updateUser(cls):
        return Column('update_user', BigInteger)
    #update_user = Column('update_user', BigInteger, ForeignKey('m_user.id'))
    @declared_attr
    def updateUserObj(cls):
        backref = 'updated' + cls.__name__ + 's'
        return relationship("User", backref=backref, primaryjoin ="foreign(User.id)==%s.updateUser" % cls.__name__)
    #update_user_obj = relationship("User", backref="update_users")
    #updateTime = Column('update_time', DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)

    @declared_attr
    def updateTime(cls):
        return Column('update_time', DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, server_default=text('NOW()'))

    @hybrid_method
    def set_insert_user(self, id):
        self.insertUser = id
        self.updateUser = id

    @hybrid_method
    def set_update_user(self, id):
        self.updateUser = id

